package com.yunbiao.ybbusstopplate.ui.fragment

import android.R.attr
import android.app.ProgressDialog
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.leon.lfilepickerlibrary.LFilePicker
import com.yunbiao.ybbusstopplate.R
import com.yunbiao.ybbusstopplate.base.BaseFragment
import com.yunbiao.ybbusstopplate.base.ContentValue
import com.yunbiao.ybbusstopplate.serialport.SerialPortConfig
import com.yunbiao.ybbusstopplate.ui.activity.MoreSettingActivity
import com.yunbiao.ybbusstopplate.utils.ProgressDialogUtils
import com.yunbiao.ybbusstopplate.utils.SpTool
import com.yunbiao.ybbusstopplate.utils.eventbus.EventMsgTool
import kotlinx.android.synthetic.main.fragment_config.*


class ConfigFragment :BaseFragment() {
    private val REQUESTCODE_FROM_ACTIVITY=110
    private var advertPath=""
    private var list:ArrayList<String>?=null
    private var typeArray:ArrayList<Int>?=null
    private var portType:Int=-1

    companion object{
        fun getInstance():ConfigFragment{
            val configFragment = ConfigFragment()
            return configFragment
        }
    }
    override fun getViewId(): Int {
        return R.layout.fragment_config
    }

    override fun initData() {
        val appVersionName = AppUtils.getAppVersionName()
        tv_version_config.text = "v$appVersionName"
        initAdvertPath()
        initSerportType()

        // 隐藏 选择路径按钮
        btn_advert_path_choice.visibility = View.GONE

        default_advert_center_path.visibility = View.GONE

        tv_advert_path.visibility = View.GONE

        img_advert_path_clean.visibility = View.GONE


    }
    private fun initAdvertPath(){
        // 隐藏
//        advertPath = SpTool.getConfigResourcePath()
//        tv_advert_path.hint=ContentValue.resoucePath
//        val path = advertPath.replace(ContentValue.sdPath, "")
//        tv_advert_path.text=path
        //tv_advert_path.visibility = View.GONE
    }
    private fun initSerportType(){
        list = arrayListOf<String>()
        list!!.add("请选择")
        for (name in SerialPortConfig.PORTNAMES){
            list!!.add(name)
        }
        typeArray= arrayListOf()
        typeArray!!.add(-1)
        for (type in SerialPortConfig.PORTTYPES){
            typeArray!!.add(type)
        }
        portType = SpTool.getConfigSerialPortType()
        var index=0
        if (portType!=-1){
            for (p in typeArray!!){
                if (p==portType){
                    break
                }
                index++
            }
        }
        val adapter = ArrayAdapter<String>(requireContext(), R.layout.myspiner, list!!)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        sp_serport.adapter=adapter
        sp_serport.setSelection(index)
    }

    override fun initListener() {
        sp_serport.onItemSelectedListener=object :AdapterView.OnItemSelectedListener{
            override fun onNothingSelected(p0: AdapterView<*>?) {

            }

            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                if(p2==0){
                    portType=-1
                }else{
                    portType = typeArray!![p2]
                }
            }

        }

        img_advert_path_clean.setOnClickListener({
            advertPath=""
            tv_advert_path.text=""
        })

        btn_advert_path_choice.setOnClickListener({
//            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
//            startActivityForResult(intent, 111)

            LFilePicker()
                .withSupportFragment(this)
                .withRequestCode(REQUESTCODE_FROM_ACTIVITY)
                .withStartPath(ContentValue.sdPath) //指定初始显示路径
                .withChooseMode(false) //选择文件夹
                .withMutilyMode(false)
                .start()
        })

        ll_set_base.setOnClickListener({
            EventMsgTool.getInstance().postDismissConfig()
        })

        btn_config_ok.setOnClickListener({
            if (portType==-1){
                ToastUtils.showShort("请选择报站器厂商")
                return@setOnClickListener
            }
//            ProgressDialogUtils.showProgressDialog(context!!,"加载配置中，请稍等...")
            showProgressDialog()
            Handler(Looper.getMainLooper()).postDelayed(object :Runnable{
                override fun run() {
                    updateConfig()
                }
            },1500)
        })

        //跳转高级设置
        btn_config_more.setOnClickListener({
            var intent=Intent(context,MoreSettingActivity::class.java)
            intent.putExtra("advertPath",advertPath)
            intent.putExtra("portType",portType)
            requireContext().startActivity(intent)
        })
    }

    private fun updateConfig(){
        val serialPortType = SpTool.getConfigSerialPortType()
        if (portType!=serialPortType){
            SpTool.cleanSiteInfo()
            //清除首末班时间
            SpTool.cleanSiteTime()
        }
        //配置更新
        SpTool.saveConfigSerialPortType(portType)
        SpTool.saveConfigResourcePath(advertPath)

//        ProgressDialogUtils.dismissProgressDialog()
        //通知更新
//        EventMsgTool.getInstance().postUpdateConig()
        if (progressDialog!=null){
            progressDialog!!.setMessage("设置成功，APP即将重启")
        }
        //重启app
        Handler(Looper.getMainLooper()).postDelayed(object :Runnable{
            override fun run() {
                if (progressDialog!=null){
                    progressDialog!!.dismiss()
                    progressDialog=null
                }
                AppUtils.relaunchApp(true)
            }

        },2000)
    }

    private var progressDialog: ProgressDialog?=null
    private fun showProgressDialog(){
        progressDialog= ProgressDialog(context)
        progressDialog!!.setMessage("正在保存，请稍候...")
        progressDialog!!.show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        LogUtils.e("requestCode--->"+requestCode)
        if (requestCode==REQUESTCODE_FROM_ACTIVITY){
            //选择文件返回
            if (data!=null){
                val filePath = data.getStringExtra("path")
                advertPath=filePath!!
                val path = advertPath.replace(ContentValue.sdPath, "")
                tv_advert_path.text=path
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        ProgressDialogUtils.dismissProgressDialog()
    }
}